package com.impetus.project.skilltest.client.pages;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.impetus.project.skilltest.client.stub.ReportingService;
import com.impetus.project.skilltest.client.stub.ReportingServiceAsync;
import com.impetus.project.skilltest.common.SkillTestException;
import com.impetus.project.skilltest.common.dataobject.ReportData;

public class TestSummaryPage {
	
	private static final ReportingServiceAsync reportService = GWT.create(ReportingService.class);
	
	private Throwable caught;
	
	public boolean loadPage(final PageData pageData)throws SkillTestException
	{
		try{
			if(pageData.getTest() == null){
				throw new SkillTestException("No associated test found to show the report.");
			}
			String candidateId = pageData.getTest().getCandidateid();
			String testId = pageData.getTest().getTestid();
			
			reportService.generateReport(candidateId, testId, new AsyncCallback<ReportData>() {
				public void onSuccess(ReportData result) {
					if(result == null){
						caught = new SkillTestException("No report data found for given test.");
					}
					// Draw the result on GUI here...
					displayResult(result, pageData);
				}
				public void onFailure(Throwable exp) {
					caught = exp;
				}
			});
			if(caught != null){
				throw caught;
			}		
			
			return true;
		}
		catch(Throwable ex){
			ex.printStackTrace();
			if(ex instanceof SkillTestException){
				throw (SkillTestException)ex;
			}else{
				throw new SkillTestException(ex);
			}
		}
	}
	
	private void displayResult(ReportData reportData, PageData pageData){
				
		final Grid grid = new Grid(4, 2);
		grid.setWidget(0, 0, new Label("Total no. of questions:"));
		grid.setWidget(1, 0, new Label("No. of questions attempted:"));
		grid.setWidget(2, 0, new Label("Total marks:"));
		grid.setWidget(3, 0, new Label("Marks obtained:"));
		
		grid.setWidget(0, 1, new Label());
		grid.setWidget(1, 1, new Label());
		grid.setWidget(2, 1, new Label());
		grid.setWidget(3, 1, new Label());
		
		HorizontalPanel submitButtonPanel = new HorizontalPanel();
		HorizontalPanel menuPanel = TopMenu.drawMenu(pageData);
		
		VerticalPanel vpanel = new VerticalPanel();
		vpanel.addStyleName("center");
		vpanel.add(menuPanel);
		vpanel.add(grid);
		vpanel.add(submitButtonPanel);
		
		RootPanel.get().clear();
	    RootPanel.get().add(vpanel);
	}
}
